package com.dingding.common.core.util.car;

import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingding.common.core.beans.carinfo.CarBrandInfo;
import com.dingding.common.core.beans.carinfo.CarModelInfo;
import com.dingding.common.core.util.HttpTool;
import com.dingding.common.core.util.car.dto.BrandFactoryInfo;

public class FetchCarInfoApi {
	
	//汽车之家网站接口返回数据的编码格式
	private static final String ENCODE = "GBK";
	
	//获取车辆所有品牌的url（汽车之家）
	private static final String BRAND_BASE_URL = "http://www.autohome.com.cn/ashx/AjaxIndexCarFind.ashx?type=1";

	//获取某个车辆品牌的所有车辆型号
	private static final String MODEL_BASE_URL = "http://www.autohome.com.cn/ashx/AjaxIndexCarFind.ashx?type=3&value=";
	
	
	/**
	 * @Description:获取汽车之家接口的请求结果
	 * @param url 被请求的地址
	 * @author fengshuonan
	 * @since 2.4
	 */
	public JSONObject fetchAutoHomeResult(String url){
		JSONObject object = HttpTool.loadJson(url,ENCODE);
		JSONObject result = object.getJSONObject("result");
		if(result == null){
			throw new RuntimeException("请求汽车之家接口的返回结果为空！");
		}else{
			return result;
		}
	}
	
	/**
	 * @Description:获取所有的车辆品牌
	 * @author fengshuonan
	 * @since 2.4
	 */
	public List<CarBrandInfo> fetchAllBrands(){
		ArrayList<CarBrandInfo> brandsArray = new ArrayList<CarBrandInfo>();
		JSONObject result = this.fetchAutoHomeResult(BRAND_BASE_URL);
		JSONArray jsonArray = result.getJSONArray("branditems");
		if(jsonArray == null || jsonArray.size() == 0){
			throw new RuntimeException("获取到的车辆品牌列表为空！");
		}
		for(int i=0;i<jsonArray.size();i++){
			CarBrandInfo carbrand = jsonArray.getObject(i, CarBrandInfo.class);
			brandsArray.add(carbrand);
		}
		return brandsArray;
	}
	
	/**
	 * @Description:根据车辆品牌的id获取旗下所有工厂
	 * @param id 车辆品牌id
	 * @author fengshuonan
	 * @since 2.4
	 */
	public List<BrandFactoryInfo> fetchAllFactorys(int id){
		ArrayList<BrandFactoryInfo> factoryArray = new ArrayList<BrandFactoryInfo>();
		JSONObject result = this.fetchAutoHomeResult(MODEL_BASE_URL + id);
		JSONArray jsonArray = result.getJSONArray("factoryitems");
		if(jsonArray == null || jsonArray.size() == 0){
			throw new RuntimeException("获取id为" + id + "的车辆品牌的所有工厂时出错！");
		}
		for(int i=0;i<jsonArray.size();i++){
			BrandFactoryInfo brandFactoryInfo = jsonArray.getObject(i, BrandFactoryInfo.class);
			factoryArray.add(brandFactoryInfo);
		}
		return factoryArray;
	}
	
	/**
	 * @Description: 获取某个车辆品牌下所有的车辆型号
	 * @param id 车辆品牌的id
	 * @author fengshuonan
	 * @since 2.4
	 */
	public List<CarModelInfo> fetchAllModels(int id){
		List<CarModelInfo> models = new ArrayList<CarModelInfo>();
		
		//首先获取该车辆品牌下所有的工厂
		List<BrandFactoryInfo> allFactorys = this.fetchAllFactorys(id);
		
		//再获取每个工厂下的所有车辆型号
		for(BrandFactoryInfo info : allFactorys){
			CarModelInfo[] factoryModels = info.getSeriesitems();
			for(CarModelInfo item : factoryModels){
				models.add(item);
			}
		}
		return models;
	}
}
